/**
* @Description: 结账日管理
* @author  qgj
* @date 2023/10/08
*/
<template>
  <div class="app-containers">
    <query-table-render
        ref="queryTable"
        :query-model="queryModel"
        :table-request="requestTableData"
        :table-column="tableColumns"
        :toolbar-render="toolbarRnd"
        :transform-query="transformQuery"
        :title-render="titleRender"
        @on-operator="onOperator"
    >
      <template v-slot:form>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryModel.type" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.account_day_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="queryModel.customerName" placeholder="请输入" clearable/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryModel.status" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.account_day_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
      </template>
    </query-table-render>

    <!-- 新增修改页面 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio
                v-for="dict in dict.type.account_day_type"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客户" prop="customerId" v-if="form.type == 'CUSTOMER'">
          <el-select
            size="small"
            v-model="form.customerId"
            placeholder="请选择"
            clearable
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="dict in customerList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提前天数" prop="advanceDay">
          <el-select
            size="small"
            v-model="form.advanceDay"
            placeholder="请选择"
            clearable
            style="width: 100%"
            @change="getMonth"
          >
            <el-option
              v-for="dict in advanceDays"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <span v-if="form.advanceDay && form.advanceDay != '-1'">本月结账日：{{form.accountDate}}</span>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model.trim="form.remark" :autosize="{ minRows: 5, maxRows: 10}" type="textarea" maxlength="500" show-word-limit placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            size="small"
            v-model="form.status"
            placeholder="请选择"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.account_day_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="saveLoading">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import QueryTableRender from "@/components/QueryTableRender";
import { listAccountDay, addAccountDay, editAccountDay, detailAccountDay, deleteAccountDay, customerOptionSelect} from "@/api/basic/closingDate";
import {checkPermi} from '@/utils/permission.js'
// import {getOrderTerminalList} from "@/api/costManagement";
// import DialogCostEdit from "@/views/costManagement/components/DialogCostEdit";
import dayjs from "dayjs"

export default {
  name: "ClosingDate",
  components: {QueryTableRender},
  dicts: ['account_day_type','account_day_status',],
  data() {
    return {
      queryModel: {
        type: '', // 类型
        status: '', // 状态
        customerName: '', // 客户名称
      },
      tableColumns: [
        {
          label: '序号',
          width: '60',
          type: 'index',
          increment: true
        },
        {
          prop: 'id',
          label: '结账日编码',
          minWidth: '200',
          showOverflowTooltip:true
        },
        {
          prop: 'type',
          label: '类型',
          minWidth: '80',
          type:'select',
          render: (h, text) => {
            let show = "";
            this.dict.type.account_day_type.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'customerName',
          label: '客户名称',
          minWidth: '260',
          showOverflowTooltip:true
        },
        {
          prop: 'advanceDay',
          label: '提前天数',
          minWidth: '100',
          showOverflowTooltip:true,
          render: (h, text) => {
            let show = "";
            if(text == '-1'){
                show = "手动";
            }else{
                show = text
            }
            return show;
          }
        },
        {
          prop: 'accountDate',
          label: '本月结账日',
          minWidth: '140',
        },
        {
          prop: 'remark',
          label: '备注',
          minWidth: '260',
          showOverflowTooltip:true
        },
        {
          prop: 'status',
          label: '状态',
          minWidth: '80',
          type:'select',
          render: (h, text) => {
            let show = "";
            this.dict.type.account_day_status.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'updaterName',
          label: '最后修改人',
          minWidth: '120',
          showOverflowTooltip:true
        },
        {
          prop: 'updateTime',
          label: '最后修改时间',
          minWidth: '160',
        },
        {
          label: '操作',
          width: '120',
          type: 'operator',
          fixed: 'right',
          operators: this.operatorsFunc()
        },
      ],
      form: {
        type: 'ALL', // 类型
        customerId: undefined, // 客户
        advanceDay: undefined, // 提前天数
        status: undefined, // 状态
        remark: undefined, // 备注
        id: undefined,
        accountDate:undefined, // 本月结账日
      },
      rules: {
        customerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        advanceDay: [
          { required: true, message: '请选择提前天数', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
      },
      saveLoading: false,
      title: '', // 弹窗标题
      open: false, // 是否显示弹窗
      customerList: [], // 客户下拉框
      advanceDays: [
        {label:"手动", value:'-1'},{label:"0", value:'0'},{label:"1", value:'1'},{label:"2", value:'2'},{label:"3", value:'3'},
        {label:"4", value:'4'},{label:"5", value:'5'},{label:"6", value:'6'},{label:"7", value:'7'},{label:"8", value:'8'},
        {label:"9", value:'9'},{label:"10", value:'10'},{label:"11", value:'11'},{label:"12", value:'12'},{label:"13", value:'13'},
        {label:"14", value:'14'},{label:"15", value:'15'},{label:"16", value:'16'},{label:"17", value:'17'},{label:"18", value:'18'},
        {label:"19", value:'19'},{label:"20", value:'20'}
      ],
    }
  },
  watch: {
    $route() {
        this.onRefreshTable();
    },
  },
  methods: {
    /**
     * 重置
     */
    resetForms() {
      this.form = {
        type: 'ALL', // 类型
        customerId: undefined, // 客户
        advanceDay: undefined, // 提前天数
        status: undefined, // 状态
        remark: undefined, // 备注
        id: undefined,
        accountDate:undefined, // 本月结账日
      };
      // this.$refs['form'].resetFields();
      this.resetForm("form");
    },
    toolbarRnd(h){
    let list = [];
      if (checkPermi(['basic-data:closing-date:add'])) {
        list.push(<el-button type="primary" icon="el-icon-plus" vOn:click={() => this.onAdd()}>新增</el-button>);
      }
      return list;
    },
    /**
     * 操作列表
     */
    operatorsFunc() {
      let list = [];
      if (checkPermi(['basic-data:closing-date:edit'])) {
        list.push({label: '修改', command: 'edit'});
      }
      if(checkPermi(['basic-data:closing-date:delete'])){
        list.push({label: '删除', command: 'delete', })
      }
      return list;
    },
    titleRender(h) {
      return <div>
        <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
        <span style="display: inline-block; color: #333333; font-size: 16px;">数据列表</span>
      </div>;
    },
    transformQuery(queryData) {
      let transParams = {}
      for (let keyName in queryData) {
        if (queryData.hasOwnProperty(keyName)) {
            transParams[keyName] = queryData[keyName]
        }
      }
      return transParams
    },
    onOperator(command, record) {
      if('edit' === command){
        this.onPreviewInvoice(record)
      }else if('delete' === command){
        this.deleteData(record)
      }
    },
    /**
     * 新增
     */
    onAdd() {
    //   this.$router.push({path: 'CustomersManageAdd'});
      this.resetForms();
      this.getCustomerOptionSelect();
      this.title = '新增';
      this.open = true;
    },
    //编辑
    onPreviewInvoice(record) {
      console.log(record)
    //   this.$router.push({path:"CustomerManageEdit",query:{customerId:JSON.stringify(record.id)}});
      this.resetForms();
      this.getCustomerOptionSelect();
      this.form = JSON.parse(JSON.stringify(record));
      this.form.advanceDay = this.form.advanceDay.toString()
      this.title = '修改';
      this.open = true;
    },
    //删除
    deleteData(record) {
      this.$modal.confirm('确定删除该结账日标准？').then(function() {
        return deleteAccountDay({id:record.id});
      }).then(() => {
        this.onRefreshTable();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
    /**
     * 获取客户信息
     */
    getCustomerOptionSelect() {
      let param = {};
      customerOptionSelect(param).then(res => {
        // console.log('res====', res);
        this.customerList = [];
        if (res.code === 200) {
          let list = res.data;
          list.forEach((item) => {
            // item.disabled = item.associated;
            // item.comName = item.code + '-' + item.name + '-' + this.filterCustomerType(item.type);
            this.customerList.push(item);
          });
        }

      }).catch(err => {

      });
    },
    /** 获取本月结账日期 */
    getMonth(val) {
        if(val != '-1'){
            let date = new Date;
            let y = date.getFullYear().toString();
            let m = (date.getMonth() + 1).toString().padStart(2, 0);
            let d = date.getDate()
            let num = new Date(y, m, 0).getDate()
            // console.log(val,y,m,d,num)
            let ds = num-val
            this.form.accountDate =  y + '年' + m + '月' + ds + '日'
        }else{
            this.form.accountDate = undefined
        }
        
    },
    /**
     * 取消
     */
     cancel() {
      this.resetForms();
      this.open = false;
    },

    /**
     * 新增或者修改
     */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          this.saveLoading = false;
          return;
        }
        let str =  JSON.parse(JSON.stringify(this.form));
        if(str.type == 'ALL'){
            str.customerId = undefined
        }
        str.accountDate = undefined
        if (str.id != undefined) {
          // 修改
          editAccountDay(str).then(res => {
            // console.log('res=', res);
            if (res) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.onRefreshTable();
              }
              this.saveLoading = false;
          }).catch(err => {
            this.saveLoading = false;
          });
        } else {
          // 新增
          addAccountDay(str).then(res => {
            // console.log('熙增=', res);
            if (res) {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.onRefreshTable();
            }
            this.saveLoading = false;
          }).catch(err => {
            this.saveLoading = false;
          });
        }
      });
    },
    filterCustomerData(query, item) {
      return item.pinyin.indexOf(query) > -1;
    },
    requestTableData(queryParams) {
      return listAccountDay(queryParams).then(respData => {
          return {
            success: true,
            total: respData.data.total,
            data: respData.data.records,
          }
        }
      );
    },
    onRefreshTable(){
      this.$refs['queryTable'].refreshTable()
    },
  }
}
</script>
<style lang="css"> 
/* .el-tooltip__popper{ max-width:30% }  */
</style>